<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="skuName">
        <el-input v-model="queryParams.skuName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['manager:sku:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manager:sku:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manager:sku:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['manager:sku:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload" size="mini" @click="handleImport"
          v-hasPermi="['manager:sku:add']">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="skuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60" align="center" prop="skuId" />
      <el-table-column label="商品名称" align="center" prop="skuName" />
      <el-table-column label="商品图片" align="center" prop="skuImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.skuImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="品牌名称" align="center" prop="brandName" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="价格" align="center" prop="price">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.price }}元</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品分类" align="center" prop="classId">
        <template slot-scope="scope">
          <div v-for="skuClass in skuClassList" :key="skuClass.classId">
            <span v-if="scope.row.classId === skuClass.classId">{{ skuClass.className }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            v-hasPermi="['manager:sku:edit']">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            v-hasPermi="['manager:sku:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="skuName">
          <el-input v-model="form.skuName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="品牌" prop="brandName">
          <el-input v-model="form.brandName" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number :min="0.01" :max="999.99" :precision="2" :step="0.5" v-model="form.price"
            placeholder="请输入商品价格" />元
        </el-form-item>
        <el-form-item label="商品类型" prop="classId">
          <!-- <el-input v-model="form.classId" placeholder="请输入商品类型" /> -->
          <el-select v-model="form.classId" placeholder="请选择商品类型">
            <el-option v-for="skuClass in skuClassList" :key="skuClass.classId" :label="skuClass.className"
              :value="skuClass.classId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="商品图片" prop="skuImage">
          <image-upload v-model="form.skuImage" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 数据导入弹窗 -->
    <el-dialog title="数据导入" :visible.sync="excelOpen" width="600px" append-to-body>
      <template>
        <el-upload ref="uploadRef" class="upload-demo" :action="uploadExcelUrl" :auto-upload="false" :headers="headers"
          :on-success="handleUploadSuccess" :on-error="handleUploadError">
          <template #trigger>
            <el-button type="primary">选择文件</el-button>
          </template>

          <el-button class="ml-3" type="success" @click="submitUpload">
            文件上传
          </el-button>

          <template #tip>
            <div class="el-upload__tip">
              只支持excel文件导入，请选择正确的文件！文件大小不超过1M.
            </div>
          </template>
        </el-upload>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listSku, getSku, delSku, addSku, updateSku } from "@/api/manager/sku";
import { listSkuClass } from "@/api/manager/skuClass";
import { loadAllParams } from "@/api/page.js";
import { getToken } from "@/utils/auth";

export default {
  name: "Sku",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      skuList: [],
      // 商品类型列表
      skuClassList: [],


      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 弹出层表单数据
      excelOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        skuName: null,
        classId: null,
      },
      // 上传文件
      uploadRef: [],

      baseUrl: process.env.VUE_APP_BASE_API,
      uploadExcelUrl: process.env.VUE_APP_BASE_API + "/manager/sku/import", // 上传excel文件地址文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        skuName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        skuImage: [
          { required: true, message: "商品图片不能为空", trigger: "blur" }
        ],
        brandName: [
          { required: true, message: "品牌名称不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        classId: [
          { required: true, message: "商品分类ID不能为空", trigger: "blur" }
        ],
        isDiscount: [
          { required: true, message: "是否参与折扣不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getSkuClassList();
  },
  methods: {
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      listSku(this.queryParams).then(response => {
        this.skuList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        skuId: null,
        skuName: null,
        skuImage: null,
        brandName: null,
        unit: null,
        price: null,
        classId: null,
        isDiscount: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.skuId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const skuId = row.skuId || this.ids
      getSku(skuId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.skuId != null) {
            updateSku(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSku(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 上传文件
    submitUpload() {
      this.$refs.uploadRef.submit();
    },

    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.fileName, url: res.fileName });
        this.excelOpen = false;
        this.$modal.msgSuccess("文件上传成功");
        this.getList();
      } else {
        this.$modal.msgError(res.msg);
      }
      this.uploadRef.clearFiles();
      this.$modal.closeLoading();
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const skuIds = row.skuId || this.ids;
      this.$modal.confirm('是否确认删除商品管理编号为"' + skuIds + '"的数据项？').then(function () {
        return delSku(skuIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('manager/sku/export', {
        ...this.queryParams
      }, `sku_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.excelOpen = true;
    },


    /* 查询商品类型列表 */
    getSkuClassList() {
      listSkuClass(loadAllParams).then(response => {
        this.skuClassList = response.rows;
      });
    },
  }
};
</script>
